local storyboard = require "storyboard"
local physics = require("physics")
local levelParser = require("levelParser")
local playerC = require("player")
local cameraC = require("camera")
local ssp = require ("SpriteSheetPacker")
local player = nil
local game

local scene = storyboard.newScene()

function scene:createScene( event )
    game = self.view    
    
    physics.start()
    physics.setGravity(0, 0)
    --physics.setTimeStep(0)
    --physics.setPositionIterations( 2 )
    --physics.setVelocityIterations( 1 )
    
    --sheets   
    local options = ssp.loadSheet ("spacesheet4.txt")
    local imageSheet = graphics.newImageSheet( "spacesheet4.png", options )
    
    print(event.params.level)
    local planetGroup,backgroundGroup = levelParser.newLevel("level"..event.params.level..".xml",imageSheet)
    game:insert(backgroundGroup)
    game:insert(planetGroup)
    player = playerC.newPlayer(imageSheet, 2, 175,155, game)
    game:insert(player)
    game:insert(player.playerSprite)
end

scene:addEventListener( "createScene", scene )


local function updateGame()
    player.updatePlayer()
    cameraC.moveCamera(game,player)
end

function scene:enterScene( event )
    game = self.view    
    
    cameraC.newCamera(game,player)
    
    
    Runtime:addEventListener("enterFrame", updateGame)
    
    local backButton = display.newRect( display.contentWidth - 60, 10, 50, 50 )
    backButton.alpha = 0.2
    local function doTouch(self, event)
        
        if event.phase == "began" then
            storyboard.gotoScene("LevelSelectionScene")
            return true
        end
    end
    
    backButton.touch = doTouch
    backButton:addEventListener("touch", backButton)
end

scene:addEventListener( "enterScene", scene )

function scene:destroyScene( event )
    if(player.planeta~=nil)then
        player.planeta = nil
    end	
end
scene:addEventListener( "destroyScene", scene )

function scene:exitScene( event )
    Runtime:removeEventListener("enterFrame", updateGame)
end
scene:addEventListener( "exitScene", scene )

return scene

